package com.jwgf.printprotocolstack;

import com.jwgf.protocolstack.ProtocolStack;
import com.jwgf.protocolstack.ProtocolStackState;
import com.jwgf.spi.SpiManager;

import android.util.Log;

public class PrintState implements ProtocolStackState {
	private int failedCnt = 0;

	@Override
	public void handleSend(ProtocolStack stack) {
		Log.i("PrintState", "Handle Send");
		if (stack.takeCmd() != null) {

			SpiManager.getInstance().write(stack.getCmdExecuting());
			SpiManager.getInstance().read(100);
		}
	}

	@Override
	public void handleRecv(ProtocolStack stack, byte[] recv) {
		Log.i("PrintState", "Handle Receive");
		if (recv[0] == 0) {

			byte[] temp = new byte[recv.length - 1];
			System.arraycopy(recv, 1, temp, 0, recv.length - 1);
			
			if (isAckOK(temp)) {
				stack.setComState(true);
				setFailedCnt(0);
				stack.notifyWriteSucceedListeners();
			} else {
				if (stack.isComStateOK()) {
					stack.setComState(false);
				}
				setFailedCnt(getFailedCnt() + 1);
				if (getFailedCnt() == 3) {
					setFailedCnt(0);
					stack.notifyWriteFailedListeners();
					stack.setComState(true);
					// clear cmd list
					stack.clearAllCmdList();
				}
			}

			stack.send();

		} else {
			{
				if (stack.isComStateOK()) {
					stack.setComState(false);
				}
				setFailedCnt(getFailedCnt() + 1);
				if (getFailedCnt() == 3) {
					setFailedCnt(0);
					stack.notifyWriteFailedListeners();
					stack.setComState(true);
					// clear cmd list
					stack.clearAllCmdList();
				}
			}
			stack.send();
		}
	}

	public int getFailedCnt() {
		return failedCnt;
	}

	public void setFailedCnt(int failedCnt) {
		this.failedCnt = failedCnt;
	}
	
	private boolean isAckOK(byte[] data) {
		for (byte ack : data) {
			if ((ack & 0xff) == 0xAA) {
				return true;
			}
		}
		return false;
	}

}
